home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_11_03 / 1103098a < prev    next >
Text File  |  1993-01-03  |  2KB  |  74 lines

  1. // date6.cpp
  2.  
  3. #include <assert.h>
  4. #include "date6.h"
  5.  
  6. inline int isleap(int y)
  7.   {return y%4 == 0 && y%100 != 0 || y%400 == 0;}
  8.  
  9. static int dtab[2][13] =
  10. {
  11.   {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
  12.   {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  13. };
  14.  
  15. Date Date::operator-(const Date& d2) const
  16. {
  17.     int months, days, years, prev_month, order;
  18.     const Date * first, * last;
  19.     
  20.     // Must know which date is first
  21.     if (compare(d2) <= 0)
  22.     {
  23.         // this <= d2
  24.         order = -1;
  25.         first = this;
  26.         last = &d2;
  27.     }
  28.     else
  29.     {
  30.         order = 1;
  31.         first = &d2;
  32.         last = this;
  33.     }
  34.     
  35.     // Compute the interval; first <= last
  36.     years = last->year - first->year;
  37.     months = last->month - first->month;
  38.     days = last->day - first->day;
  39.     assert(years >= 0 && months >= 0 && days >= 0);
  40.  
  41.     // Do obvious corrections (days before months!)
  42.     //
  43.     // This is a loop in case the previous month is
  44.     // February, and days < -28.
  45.     prev_month = last->month - 1;
  46.     while (days < 0)
  47.     {
  48.         // Borrow from the previous month
  49.         if (prev_month == 0)
  50.             prev_month = 12;
  51.         --months;
  52.         days += dtab[isleap(last->year)][prev_month--];
  53.     }
  54.  
  55.     if (months < 0)
  56.     {
  57.         // Borrow from the previous year
  58.         --years;
  59.         months += 12;
  60.     }
  61.  
  62.     // Return a date object with the interval
  63.     if (order == -1)
  64.         return Date(-months,-days,-years);
  65.     else
  66.         return Date(months,days,years);
  67. }
  68.  
  69. int Date::compare(const Date& d2) const
  70. {
  71.      // same as in Listing 2
  72. }
  73.  
  74.